package com.ice.one;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * MQ消费者
 *
 * @author : Ice-winters
 * @since : 2021-06-20 22:59
 */
public class RabbitConsumer {


    public static final String QUEUE_NAME = "zhc-queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("icewinters");
        factory.setPassword("icewinters");
        factory.setVirtualHost("/ice");
        factory.setPort(5672);
        factory.setHost("81.70.105.175");

        Connection connection = factory.newConnection("zhc-connection-consumer");

        Channel channel = connection.createChannel();

        //一次只接收一条消息
        channel.basicQos(1);

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println(new String(message.getBody()));
            // 手动发送确认消息回执
            // channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
        };

        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("消息消费被中断");
            // channel.basicNack(tag,false,true );
        };

        /**
         * 消费者 消费消息
         * 1. 消费那个队列
         * 2. 消费成功后是否自动应答   true:自动应答  false：代表手动应答 , autoAck设置为false,则需要手动确认发送回执
         * 3. 消费者成功消费消息的回调
         * 4. 消费者 消费消息 时候 中断或者取消时候 的回调函数
         */
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);



    }

}
